package com.itcncp.ucenter.web.controller;

import com.itcncp.common.base.BaseController;
import com.itcncp.common.rongCloud.models.TxtMessage;
import com.itcncp.common.util.AESUtil;
import com.itcncp.common.util.DateUtils;
import com.itcncp.common.util.Jpush;
import com.itcncp.common.util.rongCloud;
import com.itcncp.ucenter.common.ApiResult;
import com.itcncp.ucenter.common.ApiResultConstant;
import com.itcncp.ucenter.dao.model.ItcsCarBrandInfo;
import com.itcncp.ucenter.dao.model.UserCarInfo;
import com.itcncp.ucenter.dao.model.UserCarInfoExample;
import com.itcncp.ucenter.dao.model.UserCustomerInfo;
import com.itcncp.ucenter.rpc.api.ItcsCarBrandInfoService;
import com.itcncp.ucenter.rpc.api.UserCarInfoService;
import com.itcncp.ucenter.rpc.api.UserCustomerInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 *
 * Created by shuitcncp on 2016/12/10.
 */
@Controller
@RequestMapping("/plate")
@Api(tags = "plate",value = "车牌信息", description = "车牌的基本信息接口",
        produces = "produces",consumes = "consumes",basePath = "/plate")

public class UserCarController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger( UserCarController.class);

    @Autowired
    private UserCustomerInfoService userCustomerInfoService;
    @Autowired
    private UserCarInfoService userCarInfoService;
    @Autowired
    private ItcsCarBrandInfoService itcsCarBrandInfoService;


    @ApiOperation(value = "管理员审核车牌")
    @ResponseBody
    @RequestMapping(value = "/checkPlate", method = RequestMethod.POST)
    public Object create(HttpServletRequest request,
                         @RequestParam(required = true,defaultValue = "0",value = "userId") Long userId,
                         @RequestParam(required = true,defaultValue = "",value = "plate") String plate,
                         @RequestParam(required = true,defaultValue = "0",value = "isCheck") Integer isCheck,
                         @RequestParam(required = true,defaultValue = "",value = "checkMsg") String checkMsg ) {

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.FAILED);
        }

        //查询用户是否存在
        UserCustomerInfo userInfo = userCustomerInfoService.selectByPrimaryKey( userId );
        if(null == userInfo){
            return  new ApiResult( ApiResultConstant.FAILED );
        }

        //车牌验证
        if(StringUtils.isEmpty( plate )){
            return new ApiResult( ApiResultConstant.FAILED);
        }

        //车牌审核 1、未审核 2、审核通过 3、审核未通过
        if(isCheck < 0){
            return new ApiResult( ApiResultConstant.FAILED);
        }

        UserCarInfo userCarInfo = new UserCarInfo();
        userCarInfo.setUserId( userId );
        userCarInfo.setPlate( plate );
        userCarInfo.setIsCheck( isCheck.byteValue() );
        userCarInfo.setCheckMsg( checkMsg );
        userCarInfo.setUpdateTime( new Date(  ) );

        Integer total = userCarInfoService.updateByPrimaryKeySelective( userCarInfo );

        if(total>0){
            //根据用户设备号推送审核信息
            HashMap<String,String> extra = new HashMap<>(  );

            if(isCheck==2){
                extra.put( "code",String.valueOf( ApiResultConstant.APP_PLATE_SUCCESS_CHECK.getCode() ));
                checkMsg = "恭喜您，您的车牌" + plate + "已经通过审核";
                Jpush.notifiAccount(userInfo.getDeviceAppNo(),checkMsg,extra);
                //解决安卓手机必须点击通知信息BUG，顾需要使用融云透传推送
                TxtMessage txtMessage = new TxtMessage(checkMsg, extra);
                rongCloud.publishSystemMessage(rongCloud.RONGCLOUD_USERID, userInfo.getDeviceAppNo(),
                        txtMessage,checkMsg,checkMsg);

            }else{
                checkMsg = "非常遗憾的通知您，您的车牌" + plate + "审核失败!"+checkMsg;
                extra.put( "code",String.valueOf( ApiResultConstant.APP_PLATE_ERROR_CHECK.getCode() ));
                Jpush.notifiAccount(userInfo.getDeviceAppNo(),checkMsg,extra);
                //解决安卓手机必须点击通知信息BUG，顾需要使用融云透传推送
                TxtMessage txtMessage = new TxtMessage(checkMsg, extra);
                rongCloud.publishSystemMessage(rongCloud.RONGCLOUD_USERID, userInfo.getDeviceAppNo(),
                        txtMessage,checkMsg,checkMsg);

            }
            return new ApiResult( ApiResultConstant.SUCCESS);
        }

        return  new ApiResult( ApiResultConstant.FAILED );
    }

    /**
     * 车牌列表
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "获取未审核用户车牌列表")
    @ApiResponse(code=200,message = "获取未审核用户车牌列表",response = UserCarInfo.class)
    @RequestMapping(value = "/checkUser", method = RequestMethod.POST)
    public Object checkUser(HttpServletRequest request,
                            @RequestParam(required = false, defaultValue = "0", value = "pageSize") int pageSize,
                            @RequestParam(required = false, defaultValue = "5", value = "pageIndex") int pageIndex,
                            @RequestParam(required = false, defaultValue = "", value = "isLoadTime") String isLoadTime,
                            @RequestParam(required = false, defaultValue = "", value = "search") String search){

        UserCarInfoExample userCarInfoExample = new UserCarInfoExample();
        UserCarInfoExample.Criteria criteria = userCarInfoExample.createCriteria()
                .andIsCheckEqualTo( new Byte( "1" ) )
                .andDelEqualTo( new Byte( "2" ) );
        //模糊查询
        if(StringUtils.isNotEmpty( search )) {
            search = "%"+search+"%";
            userCarInfoExample.or().andPlateLike( search );
        }

        //是否加载最新的数据
        if(StringUtils.isNotEmpty( isLoadTime )){
            criteria.andCreateTimeGreaterThanOrEqualTo( DateUtils.dateFormatTimes( isLoadTime ) );
        }

        //排序
        userCarInfoExample.setOrderByClause("create_time desc");

        //分页查询
        List<UserCarInfo> userCarInfoList = userCarInfoService.selectByExampleForStartPage(userCarInfoExample,pageIndex,pageSize);

        return new ApiResult( ApiResultConstant.SUCCESS,userCarInfoList);
    }


    /**
     * 获取所有车辆品牌信息
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "获取所有车辆品牌信息")
    @ApiResponse(code=200,message = "获取所有车辆品牌信息",response = ItcsCarBrandInfo.class)
    @RequestMapping(value = "/findBrand", method = RequestMethod.POST)
    public Object findBrand(HttpServletRequest request,
                            @RequestParam(required = false, defaultValue = "0", value = "parentid") Integer parentid,
                            @RequestParam(required = false, defaultValue = "", value = "search") String search){

        //上级id为0查询所有车辆品牌信息
        List<ItcsCarBrandInfo> list = new ArrayList<ItcsCarBrandInfo>(  );

       if(parentid.equals( 0 )){
           list = itcsCarBrandInfoService.findBrand( search );
       }else{

           list = itcsCarBrandInfoService.findBrandCar( parentid );
       }

        return new ApiResult( ApiResultConstant.SUCCESS,list);

    }

    /**
     * 获取所有车辆品牌信息
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "获取品牌种类")
    @ApiResponse(code=200,message = "获取品牌种类",response = ItcsCarBrandInfo.class)
    @RequestMapping(value = "/findBrandType", method = RequestMethod.POST)
    public Object findBrand(HttpServletRequest request,
            @RequestParam(required = false, defaultValue = "0", value = "parentid") Integer parentid){

        if(parentid==0){
            parentid = 1;
        }

        //上级id为0查询所有车辆品牌信息
        List<ItcsCarBrandInfo> list = itcsCarBrandInfoService.findBrandType( parentid );

        return new ApiResult( ApiResultConstant.SUCCESS,list);
    }

//    @ApiOperation(value = "添加车辆品牌信息")
//    @ResponseBody
//    @RequestMapping(value = "/addCarBrand", method = RequestMethod.POST)
//    public Object create(HttpServletRequest request,
//                         @RequestParam(required = true,defaultValue = "0",value = "begin") Integer begin,
//                         @RequestParam(required = true,defaultValue = "0",value = "end") Integer end) {
//
////        itcsCarBrandInfoService.addBrand(begin,end);
//
//        return  new ApiResult( ApiResultConstant.SUCCESS );
//    }


    @ApiOperation(value = "添加车牌")
    @ResponseBody
    @RequestMapping(value = "/addPlate", method = RequestMethod.POST)
    public Object create(HttpServletRequest request,
                         @RequestParam(required = true,defaultValue = "0",value = "userId") Long userId,
                         @RequestParam(required = true,defaultValue = "0",value = "security") String security,
                         @RequestParam(required = true,defaultValue = "",value = "plate") String plate,
                         @RequestParam(required = true,defaultValue = "0",value = "carClass") Integer carClass,
                         @RequestParam(required = true,defaultValue = "0",value = "plateColor") Integer plateColor,
                         @RequestParam(required = true,defaultValue = "",value = "drivingLicence") String drivingLicence,
                         @RequestParam(required = true,defaultValue = "",value = "vehicleLicence") String vehicleLicence,
                         @RequestParam(required = true,defaultValue = "",value = "vehiclePhotos") String vehiclePhotos,
                         @RequestParam(required = true,defaultValue = "",value = "remark") String remark,
                         @RequestParam(required = true,defaultValue = "0",value = "carBrandId") Integer carBrandId,
                         @RequestParam(required = true,defaultValue = "0",value = "carBrandTypeId") Integer carBrandTypeId) {

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }
        //车牌验证
        if(StringUtils.isEmpty( plate )){
            return new ApiResult( ApiResultConstant.APP_PLATE_ERROR);
        }
//        //车牌验证
//        if(carClass<=0){
//            return new ApiResult( ApiResultConstant.APP_PLATE_ERROR);
//        }
//        //车牌验证
//        if(plateColor<=0){
//            return new ApiResult( ApiResultConstant.APP_PLATE_ERROR);
//        }
//        //车牌验证
//        if(StringUtils.isEmpty( drivingLicence )){
//            return new ApiResult( ApiResultConstant.APP_PLATE_ERROR);
//        }
        //车牌验证
        if(StringUtils.isEmpty( vehicleLicence )){
            return new ApiResult( ApiResultConstant.APP_PLATE_ERROR);
        }
//        //车牌验证
//        if(StringUtils.isEmpty( vehiclePhotos )){
//            return new ApiResult( ApiResultConstant.APP_PLATE_ERROR);
//        }

        //判断添加车牌时输入的安全码是否正确
        //车牌验证
        if(StringUtils.isEmpty( security )){
            return new ApiResult( ApiResultConstant.APP_SECURITY_ERROR);
        }

        UserCustomerInfo userInfo = userCustomerInfoService.selectByPrimaryKey( userId );
        if(null == userInfo){
            return new ApiResult( ApiResultConstant.APP_SECURITY_ERROR);
        }
        if(!userInfo.getSecurity().equals( AESUtil.encryptPassword( security ) )){
            return new ApiResult( ApiResultConstant.APP_SECURITY_ERROR);
        }

        //验证添加车牌数量是否超出 5辆绑定数
//        UserCarInfoExample isBindCountExample = new UserCarInfoExample();
//        isBindCountExample.createCriteria().andDelEqualTo( new Byte( "2" ) ).andUserIdEqualTo(userId);
//        Integer isBindCount = userCarInfoService.countByExample( isBindCountExample );
//        if(isBindCount>=5){
//            return  new ApiResult( ApiResultConstant.APP_PLATE_OVERFLOW_COUNT );
//        }

        UserCarInfo userCarInfo = new UserCarInfo();
        userCarInfo.setUserId( userId );
        userCarInfo.setPlate( plate );
        userCarInfo.setPlateColor( plateColor.byteValue() );
        userCarInfo.setCarClass( carClass.byteValue() );
        userCarInfo.setDrivingLicence( drivingLicence );
        userCarInfo.setVehicleLicence( vehicleLicence );
        userCarInfo.setVehiclePhotos( vehiclePhotos );
        userCarInfo.setCarBrandId( carBrandId );
        userCarInfo.setCarBrandTypeId( carBrandTypeId );
        userCarInfo.setRemark( remark );

//        userCarInfo.setIsCheck(new Byte("2"));

        userCarInfo = userCarInfoService.addUserCard( userCarInfo );

        if(null != userCarInfo){
            return new ApiResult( ApiResultConstant.SUCCESS);
        }

        return  new ApiResult( ApiResultConstant.APP_PLATE_EXIST );
    }


    @ApiOperation(value = "删除车牌")
    @ResponseBody
    @RequestMapping(value = "/delPlate", method = RequestMethod.POST)
    public Object delPlate(HttpServletRequest request,
                         @RequestParam(required = true,defaultValue = "0",value = "userId") Long userId,
                         @RequestParam(required = true,defaultValue = "",value = "plate") String plate) {

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.FAILED);
        }
        //车牌验证
        if(StringUtils.isEmpty( plate )){
            return new ApiResult( ApiResultConstant.FAILED);
        }

        UserCarInfo userCarInfo = new UserCarInfo();
        userCarInfo.setUserId( userId );
        userCarInfo.setPlate( plate );
        userCarInfo.setDel( new Byte( "1" ) );

        Integer total = userCarInfoService.updateByPrimaryKeySelective( userCarInfo );

        if(total>0){
            return new ApiResult( ApiResultConstant.SUCCESS);
        }

        return  new ApiResult( ApiResultConstant.FAILED );
    }

    /**
     * 车牌列表
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "车牌列表")
    @ApiResponse(code=200,message = "车牌列表",response = UserCarInfo.class)
    @RequestMapping(value = "/findPlate", method = RequestMethod.POST)
    public Object findPlate(HttpServletRequest request,
                               @RequestParam(required = false, defaultValue = "0", value = "userId") Long userId,
                               @RequestParam(required = false, defaultValue = "0", value = "pageSize") int pageSize,
                               @RequestParam(required = false, defaultValue = "5", value = "pageIndex") int pageIndex,
                               @RequestParam(required = false, defaultValue = "", value = "search") String search,
                               @RequestParam(required = false, value = "sort") String sort,
                               @RequestParam(required = false, value = "order")String order){

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.FAILED);
        }

        UserCarInfoExample userCarInfoExample = new UserCarInfoExample();
        UserCarInfoExample.Criteria criteria = userCarInfoExample.createCriteria();
        //数据是否删除  1、删除  2、不删除
        criteria.andDelEqualTo( new Byte( "2" ) );
        if(userId>0){
            criteria.andUserIdEqualTo( userId );
        }

        //模糊查询
        if(StringUtils.isNotEmpty(search )) {
            search = "%"+search+"%";
            userCarInfoExample.or().andPlateLike( search );
        }

        //排序
        if (StringUtils.isNotEmpty(sort) && !StringUtils.isNotEmpty(order)) {
            userCarInfoExample.setOrderByClause(sort + " " + order);
        }else{
            userCarInfoExample.setOrderByClause("plate desc");
        }
        //分页查询
        List<UserCarInfo> userCarInfoList = userCarInfoService.selectByExampleForStartPage(userCarInfoExample, pageIndex,pageSize);
        return new ApiResult( ApiResultConstant.SUCCESS,userCarInfoList);
    }


    /**
     * 判斷用戶是否已經綁定車牌
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "判斷用戶是否已經綁定車牌")
    @ApiResponse(code=200,message = "判斷用戶是否已經綁定車牌",response = UserCarInfo.class)
    @RequestMapping(value = "/isBindPlate", method = RequestMethod.POST)
    public Object isBindPlate(HttpServletRequest request,
                            @RequestParam(required = false, defaultValue = "0", value = "userId") Long userId){

        //用户id验证
        if(userId<=0){
            return new ApiResult( ApiResultConstant.FAILED);
        }

        UserCarInfoExample userCarInfoExample = new UserCarInfoExample();
        UserCarInfoExample.Criteria criteria = userCarInfoExample.createCriteria();
        //数据是否删除  1、删除  2、不删除
        criteria.andDelEqualTo( new Byte( "2" ) );
        //审核通过的车牌
        //默认审核状态 车牌审核 1、未审核 2、审核通过 3、审核未通过
        criteria.andIsCheckEqualTo(new Byte("2"));

        criteria.andUserIdEqualTo( userId );


        Integer isBindPlateCount = userCarInfoService.countByExample(userCarInfoExample);

        if(isBindPlateCount == 0){
            return new ApiResult( ApiResultConstant.FAILED);
        }

        return new ApiResult( ApiResultConstant.SUCCESS);
    }

}